import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";
import CodePush from "react-native-code-push";
import { commonStyles } from "../../configs/commonStyle";
import BasePage from "../BasePage";
import { windowHeight, windowWidth } from "../../configs/platform";
import * as Progress from "react-native-progress";

/**
 * 热更新对话框
 */
export class HotUpgradeDialog extends BasePage {
  constructor(props) {
    super(props);
    this.currProgress = 0.0;
    this.syncMessage = "";
    this.state = {
      modalVisible: false,
      immediateUpdate: false,
      updateInfo: this.props.updateInfo || {},
      progress: 0,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this._immediateUpdate();
  }


  _immediateUpdate = () => {
    this.setState({ immediateUpdate: true });
    logger("开始升级");
    CodePush.sync({ updateDialog: null, installMode: CodePush.InstallMode.IMMEDIATE },
      this.codePushStatusDidChange,
      this.codePushDownloadDidProgress,
    );
  };

  codePushStatusDidChange = (syncStatus) => {
    if (this.state.immediateUpdate) {
      switch (syncStatus) {
        case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
          this.syncMessage = "检查更新";
          break;
        case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
          this.syncMessage = "下载包";
          break;
        case CodePush.SyncStatus.AWAITING_USER_ACTION:
          this.syncMessage = "等待用户操作";
          break;
        case CodePush.SyncStatus.INSTALLING_UPDATE:
          this.syncMessage = "安装更新";
          break;
        case CodePush.SyncStatus.UP_TO_DATE:
          this.syncMessage = "应用程序是最新的";
          this.dismiss();
          break;
        case CodePush.SyncStatus.UPDATE_IGNORED:
          this.syncMessage = "用户取消更新";
          this.dismiss();
          break;
        case CodePush.SyncStatus.UPDATE_INSTALLED:
          this.syncMessage = "已安装更新，将在重新启动时应用";
          this.dismiss();
          break;
        case CodePush.SyncStatus.UNKNOWN_ERROR:
          this.syncMessage = "出现未知错误";
          this.dismiss();
          break;
      }
      logger("codePushStatusDidChange", this.syncMessage);
    }
  };

  codePushDownloadDidProgress = (progress) => {
    if (this.state.immediateUpdate) {
      this.currProgress = parseFloat(progress.receivedBytes / progress.totalBytes).toFixed(2);
      logger("下载进度", this.currProgress, progress);
      this.setState({ progress: this.currProgress });
    }
  };

  dismiss = () => {
    this.props.callback && this.props.callback();
  };

  showProgressView = () => {
    const { progress, updateInfo } = this.state;
    Log("加载进度", progress);
    return (
      <View style={{ alignItems: "center", paddingTop: 20 }}>
        <ImageBackground
          style={{ width: 247, height: 138, paddingTop: 45, paddingLeft: 30 }}
          source={require("../../images/update_image_rocket.png")}
        >
          <Text style={commonStyles.text_white_12}>v{updateInfo.appVersion}</Text>
        </ImageBackground>
        <View style={styles.content}>
          <View>
            <Text style={commonStyles.text_black666_14_25} numberOfLines={3}>{updateInfo.description}</Text>
          </View>
          <View>
            <Text style={styles.text_content}>{parseInt(progress * 100)}%</Text>
          </View>

          <Progress.Bar
            progressColor={"#92C3F8"}
            width={217}
            height={18}
            progress={progress}
            borderRadius={9}
          />
          <View>
            <Text style={styles.desc}>{progress > 0 ? "下载完成后自动安装重启" : "准备下载"}</Text>
          </View>
        </View>
      </View>
    );
  };

  render() {
    return (
      <View style={styles.modal} pointerEvents="box-none">
        {this.showProgressView()}
      </View>
    );
  }
}

let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };
export default CodePush(codePushOptions)(HotUpgradeDialog);

const styles = StyleSheet.create({
  modal: {
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.05)",
    width: windowWidth,
    height: windowHeight,
    position: "absolute",
    top: 0,
    left: 0,

  },
  content: {
    backgroundColor: "white",
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
    paddingHorizontal: 20,
    width: 247,
    top: -1,
  },
  newVersionText: {
    color: "#666666",
    fontSize: 14,
    marginTop: 10,
    marginBottom: 10,
  },
  btn: {
    width: 225,
    height: 36,
    marginTop: 10,
    marginBottom: 20,
    alignSelf: "center",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#FF5C25",
    borderRadius: 8,
  },
  desc: {
    lineHeight: 20,
    marginTop: 20,
    marginBottom: 40,
    ...commonStyles.text_gray_14,
  },
  top_bg: { width: 247, height: 165, paddingTop: 45, paddingLeft: 30 },
  text_content: {
    lineHeight: 20,
    marginTop: 20,
    marginBottom: 10,
    fontSize: 15,
    color: "#5E64E4",
  },
});


